var request = require("request");
var base_url = "";
var options, headers = {
  'content-type': 'application/x-www-form-urlencoded'
};
var util = {
  getJson: function(ops, req, res, callback) {
    options = {
      method: req.method.toString(),
      json: true
    };

    ops.params = req.app.locals._.assign(options, ops.params);
    ops.params.url = base_url + ops.params.url;
    ops.params.headers = req.app.locals._.assign(headers, ops.headers, {
      "user-token": global.token
    })
    delete ops.headers
    console.log(ops);
    request(ops.params, function(error, response, body) {
      if(callback) {
        callback(error, response, body)
      } else {
        if(!body) {
          res.json({
            "code": 500,
            "msg": "后台未响应"
          });
          return;
        };
        res.json(body);
      }
    });
  },
  encJson: function(ops, req, res, callback) {
    options = {
      method: req.method.toString(),
    };

    ops.params = req.app.locals._.assign(options, ops.params);
    ops.params.url = base_url + ops.params.url;
    ops.params.headers = req.app.locals._.assign(headers, ops.headers, {
      "user-token": global.token
    })
    delete ops.headers
    console.log(ops);
    request(ops.params, function(error, response, body) {
      if(callback) {
        callback(error, response, body)
      } else {
        if(!body) {
          res.json({
            "code": 500,
            "msg": "后台未响应"
          });
          return;
        };
        res.json(JSON.parse(body));
      }
    });
  }
};

module.exports = util;